package com.itheima.d7_thread_sync;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 目标：了解死锁
 */
public class Demo02 {

    private static final ReentrantLock lock1 = new ReentrantLock();
    private static final ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {

        /*
            解决死锁的2种方案：
                1. 可以使用相同顺序的锁
                2. 可以使用ReentrantLock的定时锁，lock.tryLock(2, TimeUnit.SECONDS);
         */

        Thread t1 = new Thread(() -> {
            try {
                lock1.lock();
                Thread.sleep(1000);
                lock2.lock();
                System.out.println("小康同学正在走路");
                lock2.unlock();
                lock1.unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                lock2.lock();
                Thread.sleep(1000);
                lock1.lock();
                System.out.println("小薇同学正在走路");
                lock1.unlock();
                lock2.unlock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }
}
